package com.sk.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.sk.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.http.HttpResponse;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;
    private final static long session_valid_timeout = 60 * 1000;
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //设置返回类型
        response.setContentType("image/jpeg");
        //禁止缓存
        response.setHeader("Progma","No-Cache");

        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            lineCaptcha.write(response.getOutputStream());
            String code = lineCaptcha.getCode();
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }@RequestMapping("/check")
    public boolean check(String inputCode,HttpSession session){
        //校验验证码生成的数据和用户输入的数据是否一致
        if (!StringUtils.hasLength(inputCode)){
            return false;
        }
        //从session中获取信息
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        long saveDate = (long)session.getAttribute(captchaProperties.getSession().getDate());
        if(inputCode.equalsIgnoreCase(savedCode)){//此处不区分大小写
            //还要先判断验证码是否过期
            if(savedCode!=null && System.currentTimeMillis()-saveDate<session_valid_timeout){
                return true;
            }

            return true;
        }
        return false;

    }

}
